package com.neusoft.bizcore.webauth.secret.userpass;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

public class UserPassAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private static ObjectMapper mapper;

    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

    private String usernameParameter = UserPassAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = UserPassAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY;

    static {
        UserPassAuthenticationFilter.mapper = new ObjectMapper();
    }

    public UserPassAuthenticationFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        final String body = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
        String username = null, password = null;
        if (StringUtils.hasText(body)) {

            final JavaType javaType = UserPassAuthenticationFilter.mapper.getTypeFactory()
                    .constructParametricType(HashMap.class, String.class, String.class);
            final Map<String, String> jsonObj =
                    UserPassAuthenticationFilter.mapper.readValue(body, javaType);
            username = this.obtainUsername(jsonObj);
            password = this.obtainPassword(jsonObj);
        }

        if (username == null) {
            username = "";
        }
        if (password == null) {
            password = "";
        }
        username = username.trim();
        final UserPassAuthenticationToken authRequest = new UserPassAuthenticationToken(
                username, password);
        return this.getAuthenticationManager().authenticate(authRequest);
    }

    protected String obtainPassword(final Map<String, String> jsonObj) {
        return jsonObj.get(this.passwordParameter);
    }

    protected String obtainUsername(final Map<String, String> jsonObj) {
        return jsonObj.get(this.usernameParameter);
    }

    public void setUsernameParameter(final String usernameParameter) {
        Assert.hasText(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }

    public void setPasswordParameter(final String passwordParameter) {
        Assert.hasText(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }

    public final String getUsernameParameter() {
        return this.usernameParameter;
    }

    public final String getPasswordParameter() {
        return this.passwordParameter;
    }

}
